import { Card } from "@/components/ui/card";
import { cn } from "@/lib/utils";
import type { Message } from "@/types/message";
import { useEffect, useRef } from "react";
import { Bot, User, Trash2, Copy } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkMath from "remark-math";
import rehypeKatex from "rehype-katex";
import remarkGfm from "remark-gfm";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism";
import "katex/dist/katex.min.css";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

interface ChatPanelProps {
  messages: Message[];
  onClear: () => void;
}

export function ChatPanel({ messages, onClear }: ChatPanelProps) {
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  // 当消息列表更新时滚动到底部
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  return (
    <div className="h-full flex flex-col overflow-hidden">
      <div className="flex-none p-4 border-b flex justify-between items-center">
        <h2 className="font-semibold">聊天记录</h2>
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <div
                role="button"
                tabIndex={0}
                onClick={onClear}
                onKeyDown={(e) => e.key === "Enter" && onClear()}
                className={cn(
                  "inline-flex items-center justify-center h-8 w-8",
                  "rounded-md transition-colors",
                  "hover:bg-accent hover:text-accent-foreground"
                )}
              >
                <Trash2 className="h-4 w-4" />
              </div>
            </TooltipTrigger>
            <TooltipContent>
              <p>清除聊天记录 (Ctrl+L)</p>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      </div>
      <div className="flex-1 overflow-y-auto">
        <div className="p-4 space-y-4">
          {messages.map((message, index) => (
            <Card
              key={message.id || index}
              className={cn(
                "p-4",
                message.role === "user" ? "ml-8 bg-primary/10" : "mr-8",
                message.type === "collecting_function" && "bg-muted",
                message.type === "loading" && "bg-muted animate-pulse",
                message.type === "success" && "bg-green-100",
                message.type === "error" && "bg-red-100"
              )}
            >
              <div className="flex flex-col gap-2">
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  {message.role === "assistant" ? (
                    <Bot className="h-4 w-4 shrink-0" />
                  ) : (
                    <User className="h-4 w-4 shrink-0" />
                  )}
                  <span>{message.role === "assistant" ? "AI 助手" : "你"}</span>
                </div>
                <div className="w-full break-words">
                  {message.type === "loading" && <div>{message.content}</div>}
                  {message.type === "collecting_function" && (
                    <div>{message.content}</div>
                  )}
                  {message.type === "success" && <div>{message.content}</div>}
                  {message.type === "error" && <div>{message.content}</div>}
                  {message.type === "text" && (
                    <div className="relative prose dark:prose-invert max-w-none overflow-x-auto break-words group">
                      <ReactMarkdown
                        remarkPlugins={[remarkMath, remarkGfm]}
                        rehypePlugins={[
                          [
                            rehypeKatex,
                            {
                              strict: false,
                              trust: true,
                              throwOnError: false,
                              errorColor: "#cc0000",
                              delimiters: [
                                { left: "$$", right: "$$", display: true },
                                { left: "$", right: "$", display: false },
                                { left: "\\[", right: "\\]", display: true },
                                { left: "\\(", right: "\\)", display: false },
                              ],
                              displayMode: false,
                              minRuleThickness: 0.05,
                              maxSize: 10,
                              maxExpand: 1000,
                              globalGroup: true,
                              output: "html",
                            },
                          ],
                        ]}
                        components={{
                          code: ({ className, children }) => {
                            const language = /language-(\w+)/.exec(
                              className || ""
                            );
                            if (
                              language &&
                              language[1].toLowerCase() === "latex"
                            ) {
                              return (
                                <div className="my-4 overflow-x-auto">
                                  <ReactMarkdown
                                    remarkPlugins={[remarkMath]}
                                    rehypePlugins={[
                                      [
                                        rehypeKatex,
                                        {
                                          displayMode: true,
                                          throwOnError: false,
                                          strict: false,
                                          trust: true,
                                          output: "html",
                                          delimiters: [
                                            {
                                              left: "$$",
                                              right: "$$",
                                              display: true,
                                            },
                                          ],
                                        },
                                      ],
                                    ]}
                                  >
                                    {`$$${String(children).trim()}$$`}
                                  </ReactMarkdown>
                                </div>
                              );
                            }
                            return language ? (
                              <SyntaxHighlighter
                                style={oneDark}
                                language={language[1]}
                                PreTag="div"
                              >
                                {String(children).replace(/\n$/, "")}
                              </SyntaxHighlighter>
                            ) : (
                              <code className={className}>{children}</code>
                            );
                          },
                        }}
                      >
                        {message.content}
                      </ReactMarkdown>
                      <div className="absolute bottom-0 right-0 p-2 opacity-0 group-hover:opacity-100 transition-opacity bg-gradient-to-l from-background to-transparent">
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <button
                                onClick={() => {
                                  navigator.clipboard.writeText(
                                    message.content
                                  );
                                  const button =
                                    document.activeElement as HTMLButtonElement;
                                  if (button) {
                                    button.blur();
                                  }
                                }}
                                className={cn(
                                  "inline-flex items-center justify-center h-8 w-8",
                                  "rounded-md transition-colors",
                                  "hover:bg-accent hover:text-accent-foreground"
                                )}
                              >
                                <Copy className="h-4 w-4" />
                              </button>
                            </TooltipTrigger>
                            <TooltipContent>
                              <p>复制原文</p>
                            </TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </Card>
          ))}
          <div ref={messagesEndRef} />
        </div>
      </div>
    </div>
  );
}
